package spring.ioc;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

/**
 * @author GY
 * @date 2019年1月10日
 * @说明: xml配置bean IOC容器加载启动阶段
 */
public class MyXmlBeanDefinitionLoad {

    // spring 资源加载器(限于classpath:下的xml资源)
    private static ResourceLoader resourceLoader = new ClassPathXmlApplicationContext();

    // bean的Definition的注册器
    private static BeanDefinitionRegistry registry = new GenericXmlApplicationContext();

    // bean的definition的读取器,将bean的definition读取到注册器中
    private static BeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(registry);

    public Resource getResurce(String path) {
        Resource resource = resourceLoader.getResource(path);
//        Resource resource = new ClassPathResource(path); 也可以这样定位resource
        return resource;
    }

    public static void main(String[] args) throws ClassNotFoundException {
        // 基本原理
        Class<?> cls = Class.forName("spring.ioc.MyXmlBeanDefinitionLoad");
        System.out.println(cls.getName());
        
        // 加载xml资源(定位，还没有真正加载内容)
        Resource resource = new MyXmlBeanDefinitionLoad().getResurce("spring-bean.xml");
        
        // 根据目标资源，获取xml中各个bean的definition内容，并且将definition注册到BeanDefinitionRegistry中
        int result = beanDefinitionReader.loadBeanDefinitions(resource);
        System.out.println(result);
        
        // return this.beanDefinitionMap.size();
        System.out.println(registry.getBeanDefinitionCount());
        
        // 通过定义的bean的名字获取bean的definition
        BeanDefinition beanDefinition = registry.getBeanDefinition("testB");
        System.out.println(beanDefinition);
        
        // 获取bean definition中的bean的Class名称
        System.out.println(beanDefinition.getBeanClassName());
    }

}
